package cn.qicaiwang.open.system.service.impl;

import cn.qicaiwang.open.system.mapper.SystemConfigMapper;
import cn.qicaiwang.open.system.model.entity.SystemConfig;
import cn.qicaiwang.open.system.model.req.SystemConfigREQ;
import cn.qicaiwang.open.system.service.ISystemConfigService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SystemConfigService extends ServiceImpl<SystemConfigMapper, SystemConfig> implements ISystemConfigService {
    @Autowired
    private SystemConfigMapper systemConfigMapper;
    @Override
    public Page<SystemConfig> pageList(Page page, SystemConfigREQ params) {
        return systemConfigMapper.page(page, params);
    }

    @Override
    @Cacheable(cacheNames = "system-config", key = "#key")
    public SystemConfig selectOneByKey(String key) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("k", key);
        queryWrapper.eq("enabled", 1);
        return systemConfigMapper.selectOne(queryWrapper);
    }

    @Override
    @CachePut(cacheNames = "system-config", key = "#systemConfig.k")
    public SystemConfig add(SystemConfig systemConfig) {
        systemConfigMapper.insert(systemConfig);
        return systemConfig;
    }

    @Override
    @CacheEvict(cacheNames = "system-config", key = "#systemConfig.k")
    public SystemConfig modify(SystemConfig systemConfig) {
        systemConfigMapper.updateById(systemConfig);
        return systemConfig;
    }

    @Override
    @CacheEvict(cacheNames = "system-config", key = "#key")
    public boolean deleteByKey(String key) {
        QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("k", key);
        return systemConfigMapper.delete(queryWrapper) > 0;
    }

    @Override
    public Page<SystemConfig> recyclebin(Page page) {
        return systemConfigMapper.recyclebin(page);
    }

    @Override
    public Boolean restore(List<String> ids) {
        int counter = 0;
        for (int i = 0; i < ids.size(); i++) {
            counter += systemConfigMapper.restore(ids.get(i));
        }
        return counter > 0;
    }

    @Override
    public Boolean clear() {
        return systemConfigMapper.clear() > 0;
    }
}
